package protocol.login;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.jboss.netty.buffer.ChannelBuffer;

import protocol.Iprotocol;
import util.ProtocolUtils;
import config.SystemDefine;

public class Login_protocol implements Iprotocol {
	private int		Type	= SystemDefine.getInstance().getLOGIN_ID();
	
	private String	names;
	
	private int		user_id;
	private int		result;
	
	private int		errorId	= 0;
	
	@Override
	public void setType(int Type) {
		this.Type = Type;
	}
	
	@Override
	public int getType() {
		return this.Type;
	}
	
	@Override
	public byte[] write() {
		
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		
		byte[] typeByteArr = ProtocolUtils.int2byteArray(Type);
		byte[] resultByteArr = ProtocolUtils.int2byteArray(result);
		
		byte[] errorArr = null;
		
		if (result < 1) {
			errorArr = ProtocolUtils.int2byteArray(errorId);
		}
		
		try {
			// skip write position
			outputStream.write(typeByteArr);
			
			outputStream.write(resultByteArr);
			if (result < 1) {
				outputStream.write(errorArr);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}
	
	@Override
	public void read(ChannelBuffer buffer) {
		int nameLength = buffer.readShort();
		byte[] nameByteArr = new byte[nameLength];
		buffer.readBytes(nameByteArr, 0, nameLength);
		
		names = new String(nameByteArr);
		
	}
	
	public String getNames() {
		return names;
	}
	
	public void setNames(String names) {
		this.names = names;
	}
	
	public int getResult() {
		return result;
	}
	
	public void setResult(int result) {
		this.result = result;
	}
	
	public int getUser_id() {
		return user_id;
	}
	
	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}
	
	public int getErrorId() {
		return errorId;
	}
	
	public void setErrorId(int errorId) {
		this.errorId = errorId;
	}
	
}
